package com.dongwu.config;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.util.ResourceUtils;

import com.dongwu.common.constants.TencentIMConstants;
import com.dongwu.manager.dto.WeiXinRedPack;

/**
 * 微信红包拼接参数
 * 
 * @author xyj
 *
 */
public class RedPackConfig {
	public static String createSendRedPackOrderSign(WeiXinRedPack redPack) {
		StringBuffer sign = new StringBuffer();
		sign.append("act_name=").append(redPack.getAct_name());
		sign.append("&client_ip=").append(redPack.getClient_ip());
		sign.append("&mch_billno=").append(redPack.getMch_billno());
		sign.append("&mch_id=").append(redPack.getMch_id());
		sign.append("&nonce_str=").append(redPack.getNonce_str());
		sign.append("&re_openid=").append(redPack.getRe_openid());
		sign.append("&remark=").append(redPack.getRemark());
		sign.append("&send_name=").append(redPack.getSend_name());
		sign.append("&total_amount=").append(redPack.getTotal_amount());
		sign.append("&total_num=").append(redPack.getTotal_num());
		sign.append("&wishing=").append(redPack.getWishing());
		sign.append("&wxappid=").append(redPack.getWxappid());
		sign.append("&key=").append(TencentIMConstants.WEIXINBUSSINESKEY);
		return DigestUtils.md5Hex(sign.toString()).toUpperCase();
	}

	@SuppressWarnings("deprecation")
	public static String SSL(String url, String data) {
		StringBuffer message = new StringBuffer();
		File WeiXinCertificate = null; // 微信商户证书

		// 获取当前系统类型
		String os = System.getProperty("os.name");
		if (os.toLowerCase().startsWith("win")) {

			try {
				// windows下获取apiclient_cert.p12的绝对路径
				WeiXinCertificate = ResourceUtils.getFile("classpath:WeiXinCertificate/apiclient_cert.p12");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			//linux下设置为linux绝对路径
			WeiXinCertificate = new File(TencentIMConstants.WEIXINCERTIFIICATEFORLINUX);
		}
		try {
			KeyStore keyStore = KeyStore.getInstance("PKCS12");
			FileInputStream instream = new FileInputStream(WeiXinCertificate);
			keyStore.load(instream, TencentIMConstants.WEIXINBUSSINESID.toCharArray());
			// Trust own CA and all self-signed certs
			SSLContext sslcontext = SSLContexts.custom()
					.loadKeyMaterial(keyStore, TencentIMConstants.WEIXINBUSSINESID.toCharArray()).build();
			// Allow TLSv1 protocol only
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
					null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
			CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
			HttpPost httpost = new HttpPost(url);

			httpost.addHeader("Connection", "keep-alive");
			httpost.addHeader("Accept", "*/*");
			httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			httpost.addHeader("Host", "api.mch.weixin.qq.com");
			httpost.addHeader("X-Requested-With", "XMLHttpRequest");
			httpost.addHeader("Cache-Control", "max-age=0");
			httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
			httpost.setEntity(new StringEntity(data, "UTF-8"));
			System.out.println("executing request" + httpost.getRequestLine());

			CloseableHttpResponse response = httpclient.execute(httpost);
			try {
				HttpEntity entity = response.getEntity();

				System.out.println("----------------------------------------");
				System.out.println(response.getStatusLine());
				if (entity != null) {
					System.out.println("Response content length: " + entity.getContentLength());
					BufferedReader bufferedReader = new BufferedReader(
							new InputStreamReader(entity.getContent(), "UTF-8"));
					String text;
					while ((text = bufferedReader.readLine()) != null) {
						message.append(text);
					}

				}
				EntityUtils.consume(entity);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				response.close();
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		return message.toString();
	}

}
